// Sokit Web Application - Clean Version
(function () {
    'use strict';

    var SokitApp = {
        ws: null,
        currentTab: 'transfer',

        // 初始化应用
        init: function () {
            this.setupWebSocket();
            this.setupTabs();
            this.setupEventListeners();
            this.log('应用程序已启动', 'info');
            
            // 延迟获取本机IP地址、转发列表和配置信息，等待WebSocket连接建立
            var self = this;
            setTimeout(function() {
                self.getLocalIPs();
                self.sendMessage('transfer_list', {});
                self.sendMessage('get_config', {});
            }, 1000);
        },

        // 设置WebSocket连接
        setupWebSocket: function () {
            var protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
            var wsUrl = protocol + '//' + location.host + '/ws';

            this.ws = new WebSocket(wsUrl);

            var self = this;
            this.ws.onopen = function () {
                self.updateConnectionStatus(true);
                self.log('WebSocket连接已建立', 'success');
            };

            this.ws.onmessage = function (event) {
                var message = JSON.parse(event.data);
                self.handleMessage(message);
            };

            this.ws.onclose = function () {
                self.updateConnectionStatus(false);
                self.log('WebSocket连接已断开', 'warning');

                // 3秒后重连
                setTimeout(function () {
                    self.setupWebSocket();
                }, 3000);
            };

            this.ws.onerror = function () {
                self.log('WebSocket连接错误', 'error');
            };
        },

        // 处理WebSocket消息
        handleMessage: function (message) {
            switch (message.type) {
                case 'client_connected':
                    this.setStatus('client-status', '已连接');
                    this.toggleButtons('client-connect', 'client-disconnect');
                    this.log('客户端已连接', 'success');
                    break;

                case 'client_disconnected':
                    this.setStatus('client-status', '未连接');
                    this.toggleButtons('client-disconnect', 'client-connect');
                    this.log('客户端已断开', 'info');
                    break;

                case 'client_data_received':
                    this.appendData('client-receive-data', '[' + message.data.time + '] ' + message.data.data);
                    break;

                case 'server_started':
                    this.setStatus('server-status', '运行中');
                    this.toggleButtons('server-start', 'server-stop');
                    this.log('服务器已启动', 'success');
                    break;

                case 'server_stopped':
                    this.setStatus('server-status', '已停止');
                    this.toggleButtons('server-stop', 'server-start');
                    this.clearConnections();
                    this.log('服务器已停止', 'info');
                    break;

                case 'server_client_connected':
                    this.addConnection(message.data.address);
                    this.log('新客户端连接: ' + message.data.address, 'success');
                    break;

                case 'server_client_disconnected':
                    this.removeConnection(message.data.address);
                    this.log('客户端断开: ' + message.data.address, 'info');
                    break;

                case 'server_data_received':
                    this.appendData('server-receive-data', '[' + message.data.time + '] ' + message.data.address + ': ' + message.data.data);
                    break;

                case 'transfer_started':
                    this.setStatus('transfer-status', '传输中');
                    this.toggleButtons('transfer-start', 'transfer-stop');
                    this.log('数据传输已开始', 'success');
                    break;

                case 'transfer_stopped':
                    this.setStatus('transfer-status', '已停止');
                    this.toggleButtons('transfer-stop', 'transfer-start');
                    this.log('数据传输已停止', 'info');
                    break;

                case 'local_ips':
                    this.updateLocalIPs(message.data.ips);
                    break;

                case 'convert_result':
                    this.updateConvertResult(message.data.result, message.data.type);
                    break;

                case 'statistics':
                    this.updateStatistics(message.data);
                    break;

                case 'statistics_reset':
                    this.log('统计信息已重置', 'info');
                    this.refreshStatistics();
                    break;

                case 'transfer_created':
                    this.log('转发创建成功: ' + message.data.name, 'success');
                    this.clearTransferForm();
                    this.refreshTransferList();
                    break;

                case 'transfer_create_failed':
                    this.log('转发创建失败: ' + message.data.error, 'error');
                    break;

                case 'transfer_list':
                    console.log('收到转发列表:', message.data.transfers);
                    this.updateTransferList(message.data.transfers);
                    break;

                case 'transfer_started':
                    this.log('转发启动成功: ' + message.data.name, 'success');
                    this.refreshTransferList();
                    break;

                case 'transfer_stopped':
                    this.log('转发停止成功: ' + message.data.name, 'info');
                    this.refreshTransferList();
                    break;

                case 'transfer_error':
                    this.log('转发错误: ' + message.data.error, 'error');
                    this.refreshTransferList();
                    break;

                case 'config':
                    this.updateUI(message.data);
                    break;

                case 'error':
                    this.log('错误: ' + message.data.message, 'error');
                    break;
            }
        },

        // 发送消息
        sendMessage: function (type, data) {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                this.ws.send(JSON.stringify({type: type, data: data}));
            } else {
                this.log('WebSocket未连接', 'error');
            }
        },

        // 设置标签页
        setupTabs: function () {
            var self = this;
            var tabBtns = document.querySelectorAll('.tab-btn');

            for (var i = 0; i < tabBtns.length; i++) {
                tabBtns[i].addEventListener('click', function () {
                    self.switchTab(this.getAttribute('data-tab'));
                });
            }
        },

        // 切换标签页
        switchTab: function (tabName) {
            // 移除所有活动状态
            var tabBtns = document.querySelectorAll('.tab-btn');
            var tabPanels = document.querySelectorAll('.tab-panel');

            for (var i = 0; i < tabBtns.length; i++) {
                tabBtns[i].classList.remove('active');
            }
            for (var i = 0; i < tabPanels.length; i++) {
                tabPanels[i].classList.remove('active');
            }

            // 添加活动状态
            document.querySelector('.tab-btn[data-tab="' + tabName + '"]').classList.add('active');
            document.getElementById(tabName).classList.add('active');

            this.currentTab = tabName;
        },

        // 设置事件监听器
        setupEventListeners: function () {
            var self = this;

            // 客户端
            this.bindClick('client-connect', function () {
                self.sendMessage('client_connect', {
                    host: self.getValue('client-host'),
                    port: self.getValue('client-port'),
                    protocol: self.getValue('client-protocol')
                });
            });

            this.bindClick('client-disconnect', function () {
                self.sendMessage('client_disconnect', {});
            });

            this.bindClick('client-send', function () {
                var data = self.getValue('client-send-data');
                if (data) {
                    self.sendMessage('client_send', {message: data});
                }
            });

            this.bindClick('client-clear', function () {
                self.clearData('client-receive-data');
            });

            // 服务器
            this.bindClick('server-start', function () {
                var port = self.getValue('server-port');
                var protocol = self.getValue('server-protocol');
                console.log('启动服务器，端口:', port, '协议:', protocol);
                self.sendMessage('server_start', {
                    port: port,
                    protocol: protocol
                });
            });

            this.bindClick('server-stop', function () {
                self.sendMessage('server_stop', {});
            });

            this.bindClick('server-send', function () {
                var data = self.getValue('server-send-data');
                if (data) {
                    self.sendMessage('server_send', {message: data});
                }
            });

            this.bindClick('server-clear', function () {
                self.clearData('server-receive-data');
            });

            // 传输 - 多实例管理
            this.bindClick('create-transfer', function () {
                var name = self.getValue('new-transfer-name');
                var localHost = self.getValue('new-local-host');
                var localPort = self.getValue('new-local-port');
                var targetHost = self.getValue('new-target-host');
                var targetPort = self.getValue('new-target-port');
                var protocol = self.getValue('new-transfer-protocol');

                if (!name || !localHost || !localPort || !targetHost || !targetPort) {
                    alert('请填写完整的转发配置');
                    return;
                }

                // UDP转发现在已经支持

                self.sendMessage('transfer_create', {
                    name: name,
                    local_host: localHost,
                    local_port: parseInt(localPort),
                    target_host: targetHost,
                    target_port: parseInt(targetPort),
                    protocol: protocol
                });
            });

            this.bindClick('refresh-transfers', function () {
                self.sendMessage('transfer_list', {});
            });

            this.bindClick('stop-all-transfers', function () {
                self.sendMessage('transfer_stop_all', {});
            });

            // 记事本
            this.bindClick('notepad-new', function () {
                self.setValue('notepad-content', '');
                self.updateNotepadStats();
            });

            this.bindClick('notepad-open', function () {
                // 创建文件输入元素
                var input = document.createElement('input');
                input.type = 'file';
                input.accept = '.txt,.log,.md,.js,.html,.css,.json,.xml,.csv';
                
                input.onchange = function(e) {
                    var file = e.target.files[0];
                    if (file) {
                        var reader = new FileReader();
                        reader.onload = function(e) {
                            var content = e.target.result;
                            self.setValue('notepad-content', content);
                            self.updateNotepadStats();
                            self.log('文件已打开: ' + file.name, 'success');
                        };
                        reader.readAsText(file, 'UTF-8');
                    }
                };
                
                input.click();
            });

            this.bindClick('notepad-save', function () {
                var content = self.getValue('notepad-content');
                if (content) {
                    // 创建下载链接
                    var blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
                    var url = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = 'notepad_' + new Date().toISOString().slice(0, 19).replace(/:/g, '-') + '.txt';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    self.log('记事本内容已保存', 'success');
                } else {
                    alert('记事本内容为空，无法保存');
                }
            });

            this.bindClick('notepad-clear', function () {
                self.clearData('notepad-content');
            });

            // 日志
            this.bindClick('log-clear', function () {
                self.clearLog();
            });

            // 记事本统计
            this.bindInput('notepad-content', function () {
                self.updateNotepadStats();
            });

            // IP地址选择
            this.bindChange('new-local-host-select', function () {
                var selectedIP = self.getValue('new-local-host-select');
                if (selectedIP) {
                    self.setValue('new-local-host', selectedIP);
                }
            });

            // 工具标签页
            this.bindClick('convert-ascii-to-hex', function () {
                var input = self.getValue('convert-input');
                if (input) {
                    self.sendMessage('convert_ascii_to_hex', {input: input});
                }
            });

            this.bindClick('convert-hex-to-ascii', function () {
                var input = self.getValue('convert-input');
                if (input) {
                    self.sendMessage('convert_hex_to_ascii', {input: input});
                }
            });

            this.bindClick('convert-clear', function () {
                self.setValue('convert-input', '');
                self.setValue('convert-output', '');
            });

            this.bindClick('stats-refresh', function () {
                self.refreshStatistics();
            });

            this.bindClick('stats-reset', function () {
                self.sendMessage('reset_statistics', {});
            });
        },

        // 绑定点击事件
        bindClick: function (id, handler) {
            var element = document.getElementById(id);
            if (element) {
                element.addEventListener('click', handler);
            }
        },

        // 绑定输入事件
        bindInput: function (id, handler) {
            var element = document.getElementById(id);
            if (element) {
                element.addEventListener('input', handler);
            }
        },

        // 绑定change事件
        bindChange: function (id, handler) {
            var element = document.getElementById(id);
            if (element) {
                element.addEventListener('change', handler);
            }
        },

        // 工具方法
        getValue: function (id) {
            var element = document.getElementById(id);
            return element ? element.value : '';
        },

        setValue: function (id, value) {
            var element = document.getElementById(id);
            if (element) {
                element.value = value;
            }
        },

        setStatus: function (id, status) {
            var element = document.getElementById(id);
            if (element) {
                element.textContent = '状态: ' + status;
            }
        },

        toggleButtons: function (disableId, enableId) {
            var disableBtn = document.getElementById(disableId);
            var enableBtn = document.getElementById(enableId);

            if (disableBtn) disableBtn.disabled = true;
            if (enableBtn) enableBtn.disabled = false;
        },

        appendData: function (id, data) {
            var element = document.getElementById(id);
            if (element) {
                element.value += data + '\n';
                element.scrollTop = element.scrollHeight;
            }
        },

        clearData: function (id) {
            var element = document.getElementById(id);
            if (element) {
                element.value = '';
            }
        },

        // 连接管理
        addConnection: function (address) {
            var container = document.getElementById('connections-container');
            var connectionDiv = document.createElement('div');
            connectionDiv.className = 'connection-item';
            connectionDiv.setAttribute('data-address', address);
            connectionDiv.innerHTML = '<span>' + address + '</span><span class="connection-status active">活跃</span>';

            // 移除占位符
            if (container.children.length === 1 && container.children[0].tagName === 'P') {
                container.innerHTML = '';
            }

            container.appendChild(connectionDiv);
        },

        removeConnection: function (address) {
            var container = document.getElementById('connections-container');
            var connectionEl = container.querySelector('[data-address="' + address + '"]');

            if (connectionEl) {
                container.removeChild(connectionEl);
            }

            // 如果没有连接了，显示占位符
            if (container.children.length === 0) {
                container.innerHTML = '<p>暂无客户端连接</p>';
            }
        },

        clearConnections: function () {
            var container = document.getElementById('connections-container');
            container.innerHTML = '<p>暂无客户端连接</p>';
        },

        // 更新连接状态
        updateConnectionStatus: function (connected) {
            var statusEl = document.getElementById('connection-status');
            if (connected) {
                statusEl.textContent = '已连接';
                statusEl.classList.add('connected');
            } else {
                statusEl.textContent = '未连接';
                statusEl.classList.remove('connected');
            }
        },

        // 更新记事本统计
        updateNotepadStats: function () {
            var content = this.getValue('notepad-content');
            var charCount = content.length;
            var lineCount = content.split('\n').length;

            var statsEl = document.getElementById('notepad-stats');
            if (statsEl) {
                statsEl.textContent = '字符数: ' + charCount + ' | 行数: ' + lineCount;
            }
        },

        // 日志记录
        log: function (message, type) {
            var logContainer = document.getElementById('log-container');
            var logEntry = document.createElement('div');
            logEntry.className = 'log-entry ' + (type || 'info');

            var timestamp = new Date().toLocaleTimeString();
            logEntry.innerHTML = '<span class="log-timestamp">' + timestamp + '</span>' + message;

            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        },

        // 清空日志
        clearLog: function () {
            var logContainer = document.getElementById('log-container');
            logContainer.innerHTML = '';
        },

        // 更新本机IP地址列表
        updateLocalIPs: function (ips) {
            var select = document.getElementById('new-local-host-select');
            if (!select) return;

            // 清空现有选项（保留第一个默认选项）
            select.innerHTML = '<option value="">选择IP地址...</option>';

            // 添加IP地址选项
            for (var i = 0; i < ips.length; i++) {
                var option = document.createElement('option');
                option.value = ips[i];
                option.textContent = ips[i] + (ips[i] === '127.0.0.1' ? ' (本地回环)' : '');
                select.appendChild(option);
            }
        },

        // 获取本机IP地址
        getLocalIPs: function () {
            this.sendMessage('get_local_ips', {});
        },

        // 更新数据转换结果
        updateConvertResult: function (result, type) {
            this.setValue('convert-output', result);
            this.log('数据转换完成: ' + type, 'success');
        },

        // 更新统计信息
        updateStatistics: function (data) {
            var current = data.current;
            var total = data.total;

            // 更新当前统计
            this.updateStatElement('stat-bytes-sent', this.formatBytes(current.bytes_sent));
            this.updateStatElement('stat-bytes-received', this.formatBytes(current.bytes_received));
            this.updateStatElement('stat-send-rate', this.formatRate(current.send_rate));
            this.updateStatElement('stat-receive-rate', this.formatRate(current.receive_rate));
            this.updateStatElement('stat-active-connections', current.active_conns);
            this.updateStatElement('stat-total-connections', total.total_connections);
            this.updateStatElement('stat-uptime', this.formatDuration(total.uptime));
        },

        // 更新统计元素
        updateStatElement: function (id, value) {
            var element = document.getElementById(id);
            if (element) {
                element.textContent = value;
                element.classList.add('updated');
                setTimeout(function () {
                    element.classList.remove('updated');
                }, 300);
            }
        },

        // 刷新统计信息
        refreshStatistics: function () {
            this.sendMessage('get_statistics', {});
        },

        // 格式化字节数
        formatBytes: function (bytes) {
            if (bytes === 0) return '0 B';
            var k = 1024;
            var sizes = ['B', 'KB', 'MB', 'GB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        },

        // 格式化传输速率
        formatRate: function (bytesPerSecond) {
            return this.formatBytes(bytesPerSecond) + '/s';
        },

        // 格式化持续时间
        formatDuration: function (seconds) {
            if (seconds < 60) {
                return Math.round(seconds) + 's';
            } else if (seconds < 3600) {
                return Math.round(seconds / 60) + 'm';
            } else if (seconds < 86400) {
                return Math.round(seconds / 3600) + 'h';
            } else {
                return Math.round(seconds / 86400) + 'd';
            }
        },

        // 转发管理相关函数
        clearTransferForm: function () {
            this.setValue('new-transfer-name', '');
            this.setValue('new-local-host', '127.0.0.1');
            this.setValue('new-local-port', '8080');
            this.setValue('new-target-host', '127.0.0.1');
            this.setValue('new-target-port', '8081');
            this.setValue('new-transfer-protocol', 'TCP');
        },

        refreshTransferList: function () {
            this.sendMessage('transfer_list', {});
        },

        updateTransferList: function (transfers) {
            console.log('更新转发列表:', transfers);
            var container = document.getElementById('transfer-list-container');
            if (!container) {
                console.error('找不到transfer-list-container元素');
                return;
            }

            if (!transfers || transfers.length === 0) {
                console.log('转发列表为空');
                container.innerHTML = '<div class="transfer-list"><div class="empty-state"><p>暂无转发服务</p><p>请在左侧创建新的转发服务</p></div></div>';
                this.updateTransferStats(0, 0, 0, 0);
                return;
            }

            var html = '';
            var totalTransfers = transfers.length;
            var runningTransfers = 0;
            var totalConnections = 0;
            var totalBytes = 0;

            for (var i = 0; i < transfers.length; i++) {
                var transfer = transfers[i];
                var isRunning = transfer.status === 'running';
                if (isRunning) runningTransfers++;
                totalConnections += transfer.connections || 0;
                totalBytes += transfer.bytes_transferred || 0;

                html += '<div class="transfer-item ' + (isRunning ? 'running' : (transfer.status === 'error' ? 'error' : '')) + '">';
                html += '<div class="transfer-header">';
                html += '<div class="transfer-name">' + this.escapeHtml(transfer.name) + '</div>';
                html += '<div class="transfer-status ' + transfer.status + '">' + this.getStatusText(transfer.status) + '</div>';
                html += '</div>';
                html += '<div class="transfer-info">';
                html += '<div class="transfer-info-item">';
                html += '<span class="transfer-info-label">本地监听:</span>';
                html += '<span>' + transfer.local_host + ':' + transfer.local_port + '</span>';
                html += '</div>';
                html += '<div class="transfer-info-item">';
                html += '<span class="transfer-info-label">目标地址:</span>';
                html += '<span>' + transfer.target_host + ':' + transfer.target_port + '</span>';
                html += '</div>';
                html += '<div class="transfer-info-item">';
                html += '<span class="transfer-info-label">连接数:</span>';
                html += '<span>' + (transfer.connections || 0) + '</span>';
                html += '</div>';
                html += '<div class="transfer-info-item">';
                html += '<span class="transfer-info-label">传输字节:</span>';
                html += '<span>' + this.formatBytes(transfer.bytes_transferred || 0) + '</span>';
                html += '</div>';
                html += '</div>';
                html += '<div class="transfer-actions">';
                if (isRunning) {
                    html += '<button class="btn btn-secondary" onclick="SokitApp.stopTransfer(\'' + transfer.id + '\')">停止</button>';
                } else {
                    html += '<button class="btn btn-primary" onclick="SokitApp.startTransfer(\'' + transfer.id + '\')">启动</button>';
                }
                html += '<button class="btn btn-secondary" onclick="SokitApp.deleteTransfer(\'' + transfer.id + '\')">删除</button>';
                html += '</div>';
                html += '</div>';
            }

            container.innerHTML = '<div class="transfer-list">' + html + '</div>';
            this.updateTransferStats(totalTransfers, runningTransfers, totalConnections, totalBytes);
        },

        updateTransferStats: function (total, running, connections, bytes) {
            this.setValue('total-transfers', total);
            this.setValue('running-transfers', running);
            this.setValue('total-connections', connections);
            this.setValue('total-bytes', this.formatBytes(bytes));
        },

        startTransfer: function (id) {
            this.sendMessage('transfer_start', { id: id });
        },

        stopTransfer: function (id) {
            this.sendMessage('transfer_stop', { id: id });
        },

        deleteTransfer: function (id) {
            if (confirm('确定要删除这个转发吗？')) {
                this.sendMessage('transfer_delete', { id: id });
            }
        },

        getStatusText: function (status) {
            switch (status) {
                case 'running': return '运行中';
                case 'stopped': return '已停止';
                case 'error': return '错误';
                default: return '未知';
            }
        },

        escapeHtml: function (text) {
            var map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, function (m) { return map[m]; });
        },

        // 根据配置更新UI
        updateUI: function (config) {
            var enabledFeatures = config.enabled_features;
            
            // 获取所有标签按钮和面板
            var tabs = ['transfer', 'client', 'server', 'tools', 'notepad'];
            var hasVisibleTabs = false;
            var firstVisibleTab = null;
            
            for (var i = 0; i < tabs.length; i++) {
                var tab = tabs[i];
                var isEnabled = enabledFeatures[tab];
                
                // 显示/隐藏标签按钮
                var tabBtn = document.querySelector('[data-tab="' + tab + '"]');
                if (tabBtn) {
                    tabBtn.style.display = isEnabled ? 'inline-flex' : 'none';
                }
                
                // 显示/隐藏面板
                var panel = document.getElementById(tab);
                if (panel) {
                    if (!isEnabled) {
                        panel.style.display = 'none';
                        panel.classList.remove('active');
                    } else {
                        if (!hasVisibleTabs) {
                            firstVisibleTab = tab;
                            hasVisibleTabs = true;
                        }
                    }
                }
            }
            
            // 确保至少有一个标签是激活的
            if (firstVisibleTab) {
                this.showTab(firstVisibleTab);
            }
            
            // 更新性能配置
            var transferConfig = config.transfer_config;
            if (transferConfig) {
                this.log('转发配置加载: 缓冲区大小 ' + transferConfig.BufferSize + ' 字节, 最大连接数 ' + transferConfig.MaxConnections, 'info');
            }
        },

        // 显示指定标签
        showTab: function (tabName) {
            this.currentTab = tabName;
            
            // 更新标签按钮状态
            var tabButtons = document.querySelectorAll('.tab-btn');
            for (var i = 0; i < tabButtons.length; i++) {
                var btn = tabButtons[i];
                if (btn.getAttribute('data-tab') === tabName) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            }
            
            // 更新面板状态
            var panels = document.querySelectorAll('.tab-panel');
            for (var i = 0; i < panels.length; i++) {
                var panel = panels[i];
                if (panel.id === tabName) {
                    panel.classList.add('active');
                } else {
                    panel.classList.remove('active');
                }
            }
        }
    };

    // 启动应用
    documentReady(function () {
        SokitApp.init();
    });

    // 全局导出
    window.SokitApp = SokitApp;
})(); 